<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/27
 * Time: 18:05
 */
namespace zhtfrontend\modules\sitepadapi\controllers;

use common\components\helpers\Fun;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use zhtfrontend\modules\sitepadapi\components\rest\ActiveController;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\filters\Cors;

class StudentController extends ActiveController
{
    public $modelClass = 'zhtfrontend\models\datas\Student';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Request-Method' => ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 3600,
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],
        ];
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionView($id)
    {
        return $this->findModel($id);
    }

    public function actionFindbycid($customer_id)
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['customer_id' => $customer_id]);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    protected function findModel($id)
    {
        $modelClass = $this->modelClass;
        $model = $modelClass::findOne($id);
        if ($model !== null) {
            return $model;
        } else {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
    }
    public function actionGetstudentinfo($student_id){
        if(empty($student_id)){
            return ['statusCode' => 200, 'message' => 'error', 'result' => '学生id为空'];
        }
        $student = (new Query())->select('s.*')->from('{{%student}} s')->where(['s.id'=>$student_id])->one();
        if (!empty($student)) {
            return ['statusCode' => 200, 'message' => 'success', 'items' => $student];
        } else {
            return ['statusCode' => 200, 'message' => 'error', 'items' => '学生信息为空'];
        }
    }

    public function actionChangestudentinfo($student_id){
        if(empty($student_id)){
            return ['statusCode' => 200, 'message' => 'error', 'result' => '学生id为空'];
        }
        $data = \Yii::$app->request->post();
        $student = (new Query())->select('*')->from('{{%student}}')->where(['id'=>$student_id])->one();
        $studentName = ArrayHelper::keyExists('student_name', $data) ? $data['student_name'] : '';
        $sex = ArrayHelper::keyExists('sex', $data) ? $data['sex'] : '男';
        $birthday = ArrayHelper::keyExists('birthday', $data) ? date('Y-m-d',strtotime($data['birthday'])) : null;
        $blood_type = ArrayHelper::keyExists('blood_type', $data) ? $data['blood_type'] : '';
        $hobby = ArrayHelper::keyExists('hobby', $data) ? $data['hobby'] : '';
        $father_phone = ArrayHelper::keyExists('father_phone', $data) ? $data['father_phone'] : '';
        $father_company = ArrayHelper::keyExists('father_company', $data) ? $data['father_company'] : '';
        $mother_phone = ArrayHelper::keyExists('mother_phone', $data) ? $data['mother_phone'] : '';
        $mother_company = ArrayHelper::keyExists('mother_company', $data) ? $data['mother_company'] : '';
        $school = ArrayHelper::keyExists('school', $data) ? $data['school'] : '';
        $address = ArrayHelper::keyExists('address', $data) ? $data['address'] : '';
        $finish_studying = ArrayHelper::keyExists('finish_studying', $data) ? $data['finish_studying'] : '';
        $intention_studying = ArrayHelper::keyExists('intention_studying', $data) ? $data['intention_studying'] : '';
        $source = ArrayHelper::keyExists('source', $data) ? $data['source'] : '';
        $card_number = ArrayHelper::keyExists('card_number', $data) ? $data['card_number'] : '';
        $company_type = ArrayHelper::keyExists('company_type', $data) ? $data['company_type'] : '';
        $main_contacts = ArrayHelper::keyExists('main_contacts', $data) ? $data['main_contacts'] : '';
        $main_phone = ArrayHelper::keyExists('main_phone', $data) ? $data['main_phone'] : '';
        $student_logo = ArrayHelper::keyExists('student_logo', $data) ? $data['student_logo'] : '';
        if(!empty($student)){
            $replace = [
                'name' => $studentName, 'birthday' => $birthday, 'sex' => $sex, 'birthday' => $birthday, 'blood_type' => $blood_type,'hobby' => $hobby,'father_phone' => $father_phone,'img'=>$student_logo,
                'father_company' => $father_company,'mother_phone' => $mother_phone,'mother_company' => $mother_company,'school' => $school,'address' => $address,'finish_studying' => $finish_studying,
                'intention_studying' => $intention_studying,'source' => $source,                'card_number' => $card_number,'company_type' => $company_type,'main_contacts' => $main_contacts,'main_phone'=>$main_phone
            ];
            \Yii::$app->db->createCommand()->update('{{%student}}', $replace, ['id' => $student_id])->execute();
            /**改成更改student表的img字段了，与customer无关了if(!empty($student_logo)){
                \Yii::$app->db->createCommand()->update('{{%customer}}', ['logo' => $student_logo], ['id' => $student['customer_id']])->execute();
            }*/
            return ['statusCode' => 200, 'message' => 'success', 'items' => '更改学员信息成功'];
        }else{
            /*就算有增加学员的功能也要先设计添加的学员所属的会员，要不然也是个废的*/
            $student_data = [
                'name' => $studentName, 'birthday' => $birthday, 'sex' => $sex, 'birthday' => $birthday, 'blood_type' => $blood_type,'hobby' => $hobby,'father_phone' => $father_phone,'img'=>$student_logo,
                'father_company' => $father_company,'mother_phone' => $mother_phone,'mother_company' => $mother_company,'school' => $school,'address' => $address,'finish_studying' => $finish_studying,
                'intention_studying' => $intention_studying,'source' => $source,                'card_number' => $card_number,'company_type' => $company_type,'main_contacts' => $main_contacts,'main_phone'=>$main_phone
            ];
            \Yii::$app->db->createCommand()->insert('{{%student}}', $student_data)->execute();
            return ['statusCode' => 200, 'message' => 'error', 'result' => '学员信息为空'];
        }
    }

    //获取学员列表
    public function actionGetstudents(){
        $post = \Yii::$app->request->post();
        $site_id = Fun::getSiteId();
        $query = (new Query())->select(['s.id as id','s.name as name','s.sex as sex','s.img as logo','s.main_contacts as main_contacts','s.main_phone as main_phone'])->from('{{%student}} s')->leftJoin('{{%customer}} c','c.id=s.customer_id');
        $query->where(['s.site_id'=>$site_id]);
        if(!empty($post) && !empty($post['content'])){
            if (preg_match("/^\w{6}$/",$post['content'])){//当输入的是激活码的时候
                $cardattr = (new Query())->select(['customer_id'])->from('{{%card_attr}}')->where(['v_code'=>$post['content']])->one();
                if(!empty($cardattr)){
                    $query->andWhere(['c.id'=>$cardattr['customer_id']]);
                }else{
                    $query->andWhere(['1'=>'2']);
                }
            }else{
                $query->andWhere(['like', 's.name', $post['content']]);
            }
        }
        $students = $query->all();
        $data = [];
        foreach ($students as $k => $v) {
            $data[] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'sex' => $v['sex'],
                'logo' => $v['logo'],
                'main_contacts' => $v['main_contacts'],
                'main_phone' => $v['main_phone']
            ];
        }
        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 6
            ],
        ]);
//        if(!empty($students)){
//            return ['statusCode' => 200, 'message' => 'success','items'=>$students];
//        }else{
//            return ['statusCode' => 200, 'message' => 'error', 'result' => '学员信息列表为空'];
//        }
    }
}